<template>
  <div class="check-planner-container">
    <el-card shadow="never" class="header-card">
      <div class="page-header">
        <div class="header-content">
          <el-icon class="header-icon" :size="28"><Calendar /></el-icon>
          <div class="header-text">
            <h2>盘点计划生成器</h2>
            <p>智能生成盘点计划，优化盘点效率</p>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 步骤指示器 -->
    <el-card shadow="never" class="steps-card">
      <el-steps :active="currentStep" align-center>
        <el-step title="选择策略" icon="Setting" />
        <el-step title="配置参数" icon="Edit" />
        <el-step title="预览计划" icon="View" />
        <el-step title="生成任务" icon="CircleCheck" />
      </el-steps>
    </el-card>

    <!-- 步骤1：选择策略 -->
    <el-card shadow="never" v-if="currentStep === 0" class="content-card">
      <div class="section-title">
        <el-icon><SetUp /></el-icon>
        <span>选择盘点策略</span>
      </div>
      
      <div class="strategy-grid">
        <div 
          v-for="strategy in strategies" 
          :key="strategy.id"
          class="strategy-card"
          :class="{ 'selected': selectedStrategy === strategy.id }"
          @click="selectedStrategy = strategy.id"
        >
          <div class="strategy-icon">
            <el-icon :size="40">
              <component :is="strategy.icon" />
            </el-icon>
          </div>
          <div class="strategy-info">
            <h3>{{ strategy.name }}</h3>
            <p>{{ strategy.desc }}</p>
            <div class="strategy-tags">
              <el-tag size="small" type="info">{{ strategy.frequency }}</el-tag>
              <el-tag size="small" type="success">{{ strategy.coverage }}</el-tag>
            </div>
          </div>
          <div class="strategy-check" v-if="selectedStrategy === strategy.id">
            <el-icon color="#67C23A" :size="30"><CircleCheckFilled /></el-icon>
          </div>
        </div>
      </div>

      <div class="step-actions">
        <el-button type="primary" size="large" @click="currentStep = 1" :disabled="!selectedStrategy">
          下一步
          <el-icon><ArrowRight /></el-icon>
        </el-button>
      </div>
    </el-card>

    <!-- 步骤2：配置参数 -->
    <el-card shadow="never" v-if="currentStep === 1" class="content-card">
      <div class="section-title">
        <el-icon><Edit /></el-icon>
        <span>配置盘点参数</span>
      </div>

      <el-form :model="planForm" :rules="planRules" ref="planFormRef" label-width="140px" style="max-width: 800px;">
        <el-divider content-position="left">基本信息</el-divider>
        
        <el-form-item label="计划名称" prop="planName">
          <el-input v-model="planForm.planName" placeholder="如：2024年第一季度盘点计划" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker v-model="planForm.startDate" type="date" placeholder="选择开始日期" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker v-model="planForm.endDate" type="date" placeholder="选择结束日期" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">盘点范围</el-divider>

        <el-form-item label="盘点仓库" prop="warehouses">
          <el-select v-model="planForm.warehouses" multiple placeholder="选择仓库" style="width: 100%">
            <el-option label="主仓库" :value="1" />
            <el-option label="分仓A" :value="2" />
            <el-option label="分仓B" :value="3" />
            <el-option label="次品仓" :value="4" />
          </el-select>
        </el-form-item>

        <el-form-item label="商品范围" prop="productScope">
          <el-radio-group v-model="planForm.productScope">
            <el-radio label="all">全部商品</el-radio>
            <el-radio label="abc">ABC分类</el-radio>
            <el-radio label="category">按分类</el-radio>
            <el-radio label="custom">自定义</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="ABC分类" v-if="planForm.productScope === 'abc'">
          <el-checkbox-group v-model="planForm.abcLevels">
            <el-checkbox label="A">A类商品（高价值）</el-checkbox>
            <el-checkbox label="B">B类商品（中价值）</el-checkbox>
            <el-checkbox label="C">C类商品（低价值）</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-divider content-position="left">高级配置</el-divider>

        <el-form-item label="自动分配任务">
          <el-switch v-model="planForm.autoAssign" active-text="自动" inactive-text="手动" />
          <span class="form-tip">根据人员工作量自动分配盘点任务</span>
        </el-form-item>

        <el-form-item label="工作时间" v-if="planForm.autoAssign">
          <el-time-picker
            v-model="planForm.workTime"
            is-range
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="HH:mm"
          />
        </el-form-item>

        <el-form-item label="并发任务数">
          <el-input-number v-model="planForm.concurrentTasks" :min="1" :max="10" />
          <span class="form-tip">同时进行的盘点任务数量</span>
        </el-form-item>

        <el-form-item label="智能推荐">
          <el-switch v-model="planForm.smartRecommend" active-text="开启" inactive-text="关闭" />
          <span class="form-tip">AI分析历史数据，优化盘点顺序</span>
        </el-form-item>
      </el-form>

      <div class="step-actions">
        <el-button size="large" @click="currentStep = 0">
          <el-icon><ArrowLeft /></el-icon>
          上一步
        </el-button>
        <el-button type="primary" size="large" @click="handleGeneratePreview">
          下一步
          <el-icon><ArrowRight /></el-icon>
        </el-button>
      </div>
    </el-card>

    <!-- 步骤3：预览计划 -->
    <el-card shadow="never" v-if="currentStep === 2" class="content-card">
      <div class="section-title">
        <el-icon><View /></el-icon>
        <span>预览盘点计划</span>
      </div>

      <el-alert
        title="计划预览"
        type="success"
        :closable="false"
        style="margin-bottom: 20px;"
      >
        <template #default>
          将生成 <strong>{{ previewTasks.length }}</strong> 个盘点任务，
          预计耗时 <strong>{{ estimatedDays }}</strong> 天，
          涉及 <strong>{{ estimatedProducts }}</strong> 个商品
        </template>
      </el-alert>

      <el-table :data="previewTasks" stripe border max-height="500">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="taskName" label="任务名称" min-width="200" />
        <el-table-column prop="type" label="类型" width="120">
          <template #default="{ row }">
            <el-tag>{{ row.type }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="warehouseName" label="仓库" width="120" />
        <el-table-column prop="productCount" label="商品数" width="100" align="right" />
        <el-table-column prop="scheduledDate" label="计划日期" width="120" />
        <el-table-column prop="estimatedHours" label="预计耗时" width="120">
          <template #default="{ row }">
            {{ row.estimatedHours }}小时
          </template>
        </el-table-column>
        <el-table-column prop="assignedTo" label="建议负责人" width="120" />
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :type="getPriorityTag(row.priority)">{{ row.priority }}</el-tag>
          </template>
        </el-table-column>
      </el-table>

      <div class="step-actions">
        <el-button size="large" @click="currentStep = 1">
          <el-icon><ArrowLeft /></el-icon>
          上一步
        </el-button>
        <el-button type="success" size="large" @click="handleGenerate" :loading="generating">
          <el-icon><CircleCheck /></el-icon>
          生成盘点任务
        </el-button>
      </div>
    </el-card>

    <!-- 步骤4：生成成功 -->
    <el-card shadow="never" v-if="currentStep === 3" class="content-card success-card">
      <el-result
        icon="success"
        title="盘点计划生成成功！"
        :sub-title="`已成功生成${previewTasks.length}个盘点任务`"
      >
        <template #extra>
          <el-button type="primary" size="large" @click="$router.push('/inventory/check-tasks')">
            <el-icon><View /></el-icon>
            查看盘点任务
          </el-button>
          <el-button size="large" @click="handleReset">
            <el-icon><RefreshRight /></el-icon>
            继续生成
          </el-button>
        </template>
      </el-result>

      <div class="success-summary">
        <h3>生成摘要</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="计划名称">{{ planForm.planName }}</el-descriptions-item>
          <el-descriptions-item label="计划周期">{{ planForm.startDate }} 至 {{ planForm.endDate }}</el-descriptions-item>
          <el-descriptions-item label="涉及仓库">{{ planForm.warehouses.length }}个</el-descriptions-item>
          <el-descriptions-item label="生成任务">{{ previewTasks.length }}个</el-descriptions-item>
          <el-descriptions-item label="预计商品">{{ estimatedProducts }}个</el-descriptions-item>
          <el-descriptions-item label="预计耗时">{{ estimatedDays }}天</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, markRaw } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Calendar, Setting, Edit, View, CircleCheck, SetUp, ArrowRight,
  ArrowLeft, RefreshRight, CircleCheckFilled,
  Grid, Refresh, Lightning, Coin, TrendCharts, MagicStick
} from '@element-plus/icons-vue'

const router = useRouter()

// 状态
const currentStep = ref(0)
const selectedStrategy = ref(null)
const generating = ref(false)
const planFormRef = ref(null)

// 策略列表
const strategies = ref([
  {
    id: 1,
    name: '全盘策略',
    desc: '对所有商品进行全面盘点，适合年度盘点或重大库存调整',
    icon: markRaw(Grid),
    frequency: '年度',
    coverage: '100%覆盖'
  },
  {
    id: 2,
    name: 'ABC分类策略',
    desc: 'A类商品每月盘，B类商品每季盘，C类商品每半年盘',
    icon: markRaw(TrendCharts),
    frequency: '分级',
    coverage: '智能分配'
  },
  {
    id: 3,
    name: '循环盘点策略',
    desc: '将商品分组，每周盘点一组，确保每个商品定期被盘点',
    icon: markRaw(Refresh),
    frequency: '每周',
    coverage: '分批覆盖'
  },
  {
    id: 4,
    name: '高风险商品策略',
    desc: '优先盘点高价值、易损耗、高周转率的商品',
    icon: markRaw(Lightning),
    frequency: '每月',
    coverage: '重点商品'
  },
  {
    id: 5,
    name: '季度盘点策略',
    desc: '每季度进行一次全面盘点，平衡效率与准确性',
    icon: markRaw(Calendar),
    frequency: '每季度',
    coverage: '全面覆盖'
  },
  {
    id: 6,
    name: '智能推荐策略',
    desc: 'AI分析历史数据，智能推荐最优盘点方案',
    icon: markRaw(MagicStick),
    frequency: '智能',
    coverage: 'AI优化'
  }
])

// 计划表单
const planForm = reactive({
  planName: '',
  startDate: '',
  endDate: '',
  warehouses: [],
  productScope: 'all',
  abcLevels: ['A', 'B', 'C'],
  autoAssign: true,
  workTime: [new Date(2024, 0, 1, 8, 0), new Date(2024, 0, 1, 18, 0)],
  concurrentTasks: 2,
  smartRecommend: true
})

// 表单验证规则
const planRules = {
  planName: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
  startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }],
  warehouses: [{ required: true, message: '请选择至少一个仓库', trigger: 'change' }]
}

// 预览任务
const previewTasks = ref([])

// 计算属性
const estimatedDays = computed(() => {
  if (planForm.startDate && planForm.endDate) {
    const days = Math.ceil((new Date(planForm.endDate) - new Date(planForm.startDate)) / (1000 * 60 * 60 * 24))
    return days > 0 ? days : 1
  }
  return 0
})

const estimatedProducts = computed(() => {
  return previewTasks.value.reduce((sum, task) => sum + task.productCount, 0)
})

// 方法
const handleGeneratePreview = () => {
  planFormRef.value.validate((valid) => {
    if (valid) {
      // 生成预览任务
      generatePreviewTasks()
      currentStep.value = 2
    }
  })
}

const generatePreviewTasks = () => {
  const strategy = strategies.value.find(s => s.id === selectedStrategy.value)
  const tasks = []
  
  // 根据不同策略生成任务
  if (selectedStrategy.value === 1) {
    // 全盘策略
    planForm.warehouses.forEach((whId, index) => {
      tasks.push({
        taskName: `${planForm.planName} - ${getWarehouseName(whId)}全盘`,
        type: '全盘',
        warehouseId: whId,
        warehouseName: getWarehouseName(whId),
        productCount: 500 + index * 100,
        scheduledDate: formatDate(addDays(planForm.startDate, index * 2)),
        estimatedHours: 16,
        assignedTo: '待分配',
        priority: '高'
      })
    })
  } else if (selectedStrategy.value === 2) {
    // ABC分类策略
    const abcTasks = []
    planForm.warehouses.forEach((whId, whIndex) => {
      if (planForm.abcLevels.includes('A')) {
        abcTasks.push({
          taskName: `${planForm.planName} - ${getWarehouseName(whId)} A类商品`,
          type: 'ABC-A类',
          warehouseId: whId,
          warehouseName: getWarehouseName(whId),
          productCount: 50,
          scheduledDate: formatDate(addDays(planForm.startDate, whIndex * 3)),
          estimatedHours: 4,
          assignedTo: '张三',
          priority: '高'
        })
      }
      if (planForm.abcLevels.includes('B')) {
        abcTasks.push({
          taskName: `${planForm.planName} - ${getWarehouseName(whId)} B类商品`,
          type: 'ABC-B类',
          warehouseId: whId,
          warehouseName: getWarehouseName(whId),
          productCount: 150,
          scheduledDate: formatDate(addDays(planForm.startDate, whIndex * 3 + 1)),
          estimatedHours: 6,
          assignedTo: '李四',
          priority: '中'
        })
      }
      if (planForm.abcLevels.includes('C')) {
        abcTasks.push({
          taskName: `${planForm.planName} - ${getWarehouseName(whId)} C类商品`,
          type: 'ABC-C类',
          warehouseId: whId,
          warehouseName: getWarehouseName(whId),
          productCount: 300,
          scheduledDate: formatDate(addDays(planForm.startDate, whIndex * 3 + 2)),
          estimatedHours: 8,
          assignedTo: '王五',
          priority: '低'
        })
      }
    })
    tasks.push(...abcTasks)
  } else if (selectedStrategy.value === 3) {
    // 循环盘点策略
    const weeks = Math.ceil(estimatedDays.value / 7)
    for (let i = 0; i < weeks; i++) {
      planForm.warehouses.forEach((whId) => {
        tasks.push({
          taskName: `${planForm.planName} - 第${i + 1}周 ${getWarehouseName(whId)}`,
          type: '循环盘点',
          warehouseId: whId,
          warehouseName: getWarehouseName(whId),
          productCount: 120,
          scheduledDate: formatDate(addDays(planForm.startDate, i * 7)),
          estimatedHours: 6,
          assignedTo: i % 2 === 0 ? '张三' : '李四',
          priority: '中'
        })
      })
    }
  } else {
    // 其他策略的简化实现
    planForm.warehouses.forEach((whId, index) => {
      tasks.push({
        taskName: `${planForm.planName} - ${getWarehouseName(whId)}`,
        type: strategy.name,
        warehouseId: whId,
        warehouseName: getWarehouseName(whId),
        productCount: 200 + index * 50,
        scheduledDate: formatDate(addDays(planForm.startDate, index)),
        estimatedHours: 8,
        assignedTo: '待分配',
        priority: '中'
      })
    })
  }
  
  previewTasks.value = tasks
}

const handleGenerate = () => {
  generating.value = true
  
  setTimeout(() => {
    generating.value = false
    currentStep.value = 3
    ElMessage.success('盘点计划生成成功！')
  }, 1500)
}

const handleReset = () => {
  currentStep.value = 0
  selectedStrategy.value = null
  previewTasks.value = []
  Object.assign(planForm, {
    planName: '',
    startDate: '',
    endDate: '',
    warehouses: [],
    productScope: 'all',
    abcLevels: ['A', 'B', 'C'],
    autoAssign: true,
    workTime: [new Date(2024, 0, 1, 8, 0), new Date(2024, 0, 1, 18, 0)],
    concurrentTasks: 2,
    smartRecommend: true
  })
}

// 工具函数
const getWarehouseName = (id) => {
  const map = { 1: '主仓库', 2: '分仓A', 3: '分仓B', 4: '次品仓' }
  return map[id] || `仓库${id}`
}

const addDays = (date, days) => {
  const result = new Date(date)
  result.setDate(result.getDate() + days)
  return result
}

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

const getPriorityTag = (priority) => {
  const map = { '高': 'danger', '中': 'warning', '低': 'info' }
  return map[priority] || ''
}
</script>

<style scoped>
.check-planner-container {
  padding: 20px;
}

.header-card,
.steps-card,
.content-card {
  margin-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  color: #409EFF;
}

.header-text h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.header-text p {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: #909399;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 24px;
  padding-bottom: 12px;
  border-bottom: 2px solid #e4e7ed;
}

.strategy-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-bottom: 30px;
}

.strategy-card {
  position: relative;
  padding: 24px;
  border: 2px solid #e4e7ed;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s;
  background: white;
}

.strategy-card:hover {
  border-color: #409EFF;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
  transform: translateY(-4px);
}

.strategy-card.selected {
  border-color: #67C23A;
  background: #f0f9ff;
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
}

.strategy-icon {
  display: flex;
  justify-content: center;
  margin-bottom: 16px;
  color: #409EFF;
}

.strategy-info h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  color: #303133;
}

.strategy-info p {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
}

.strategy-tags {
  display: flex;
  gap: 8px;
}

.strategy-check {
  position: absolute;
  top: 12px;
  right: 12px;
}

.step-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 30px;
}

.form-tip {
  margin-left: 12px;
  font-size: 13px;
  color: #909399;
}

.success-card {
  min-height: 400px;
}

.success-summary {
  margin-top: 30px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
}

.success-summary h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: #303133;
}

@media (max-width: 1200px) {
  .strategy-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .strategy-grid {
    grid-template-columns: 1fr;
  }
}
</style>

